/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.SafetyInspection;
import com.koron.scene.domain.SafetyInspectionFileBean;
import com.koron.scene.service.api.SafetyInspectionService;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "safetyInspection", description = "安全巡查日志接口")
@RestController
@RequestMapping("/safetyInspection")
public class SafetyInspectionController {

    private final static Logger logger = LoggerFactory.getLogger(SafetyInspectionController.class);
    @Autowired
    private SafetyInspectionService service;

    @ApiOperation("保存安全巡查日志接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id,新增不传，修改必传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectName", value = "工程名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "inspectionDate", value = "巡查日期", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "week", value = "星期", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "morningWeather", value = "上午天气" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "afternoonWeather", value = "下午天气" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "nightWeather", value = "夜间天气" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "constructionContent", value = "施工内容" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "inspectionCondition", value = "安全检查情况" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "treatmentMeasures", value = "处理措施" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hiddenRectification", value = "施工单位隐患整改情况" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "highRiskSafetyStatus", value = "危险性较大分部分项工程安全状况" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "others", value = "其他" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "safetySupervisor", value = "安全监理员" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "safetySupervisorName", value = "安全监理员名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "chiefSupervisoryEngineer", value = "总监理工程师" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "chiefSupervisoryEngineerName", value = "总监理工程师名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reviewDate", value = "审阅日期" , dataType = "String", paramType = "query")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存安全巡查日志接口",businessModule = "安全巡查", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<String> save(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore SafetyInspection bean,
                                     MultipartFile[] files, String keepFiles, String keepPreviewFiles, String delFiles, String delPreviewFiles) {
        MessageBean<String> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return service.save(bean, user,files,keepFiles,keepPreviewFiles,delFiles,delPreviewFiles);
    }

    @ApiOperation("保存安全巡查日志附件接口")
    @RequestMapping(value = "/saveFiles.htm", method = RequestMethod.POST)
    @Log(title = "保存安全巡查日志接口",businessModule = "安全巡查", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> saveFiles(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id,  @ApiIgnore SafetyInspectionFileBean fileBean) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return ADOConnection.runTask(factory -> service.saveFiles(factory, id,user,fileBean), MessageBean.class);
    }

    @ApiOperation("保存安全巡查日志附件接口")
    @RequestMapping(value = "/saveFile.htm", method = RequestMethod.POST)
    @Log(title = "保存安全巡查日志接口",businessModule = "安全巡查", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> saveFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id, Integer type, MultipartFile[] files) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return ADOConnection.runTask(factory -> service.saveFile(factory, id,user,type,files), MessageBean.class);
    }

    @ApiOperation("删除附件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "fileUrl", value = "要删除的附件地址", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "filePreUrl", value = "要删除的预览地址", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/delFile.htm", method = RequestMethod.POST)
    public MessageBean<Integer> deleteFile(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id, @RequestParam final Integer type, @RequestParam final String fileUrl, @RequestParam final String filePreUrl) {
        MessageBean<Integer> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return ADOConnection.runTask(factory -> service.delFile(factory, id,user,type,fileUrl,filePreUrl), MessageBean.class);
    }


    @ApiOperation("获取附件列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "巡查id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/fileList.htm", method = RequestMethod.POST)
    public MessageBean<Map> fileList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,@RequestParam final String id,@RequestParam final Integer type) {
        MessageBean<Map> messageBean = new MessageBean<>();
        if (null == user) {
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return ADOConnection.runTask(factory -> service.fileList(factory, id,user,type), MessageBean.class);
    }

    @ApiOperation("删除安全巡查日志接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除安全巡查",businessModule = "安全巡查", businessManipulation = BusinessManipulation.DELETE)

    public MessageBean<Integer> delete(@RequestParam final String id, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.delete(id, user);
    }


    @ApiOperation("查询安全巡查日志详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<SafetyInspection> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            MessageBean<SafetyInspection> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        return service.queryOne(id);
    }

    @ApiOperation("安全巡查日志列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectName", value = "工程名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始日期" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "截止日期" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "String", paramType = "query"),

    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public MessageBean<DataBean> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam(required = false) final String corpCode,
                                      @RequestParam(required = false) final String projectName,
                                      @RequestParam(required = false) final String startTime,
                                      @RequestParam(required = false) final String endTime,
                                      @RequestParam(required = false) String keyword,
                                      @RequestParam Integer page,
                                      @RequestParam Integer pageSize) {
        if (null == user) {
            MessageBean<DataBean> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LONGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return messageBean;
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean> msg = service.list(corpCode, projectName, startTime, endTime,keyword, start, pageSize);
        if (null != msg.getData())
            msg.getData().setPageNo(page);
        return msg;
    }

    @ApiOperation("安全巡查日志导出")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/exports.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exports(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            return null;
        }
        MessageBean<SafetyInspection> msg = service.queryOne(id);
        if (null == msg.getData()) {
            return null;
        }
        SafetyInspection inspection = msg.getData();
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        Date inspectionDate = inspection.getInspectionDate();
        Date reviewDate = inspection.getReviewDate();
        inspection.setInspectionDateStr(sdf.format(inspectionDate));
        inspection.setReviewDateStr(sdf.format(reviewDate));
        map.put("data", inspection);
        File targetFile = new File("static/excel/safetyInspection.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/safetyInspection.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("安全巡查日志", targetFile, "safetyInspection.btl", map);
    }
}
